package com.open.party.cloud.view.examine

import android.os.Bundle
import android.view.View
import androidx.core.content.ContextCompat
import cn.android.x.model.data.ResultInfo
import cn.android.x.parent.AppEventBusTitleBaseActivity
import cn.sinothk.map.amap.base.MapCallback
import cn.sinothk.map.amap.location.AMapLocate
import cn.sinothk.map.amap.location.AMapLocationEntity
import com.open.party.cloud.R
import com.open.party.cloud.model.AttendanceEntity
import com.open.party.cloud.model.AttendanceVO
import com.open.party.cloud.model.data.LocalCache
import com.open.party.cloud.viewModel.ExamineViewModel
import com.sinothk.android.utils.XUtils
import kotlinx.android.synthetic.main.examine_class_do_attendance_activity.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.text.SimpleDateFormat
import java.util.*

class ExamineClassDoAttendanceActivity : AppEventBusTitleBaseActivity() {
    var attendanceVO = AttendanceVO()
    var classId: String? = null
    var viewModel: ExamineViewModel? = null
    var thread: Thread? = null

    private fun initView() {
        initTimer()

        AMapLocate().locationOnce(this, object : MapCallback<AMapLocationEntity> {
            override fun onFail(msg: String?) {
                runOnUiThread {
                    XUtils.toast().show(msg)
                }
            }

            override fun onSuccess(mapInfo: AMapLocationEntity) {
                attendanceVO.lat = mapInfo.latitude
                attendanceVO.lng = mapInfo.longitude
                attendanceVO.address = mapInfo.address
                addressTv.text = XUtils.string().getNotNullValue(mapInfo.address)
            }
        })

        // 签到类型
        attendanceVO.checkType = "sign"
    }

    override fun onDestroy() {
        super.onDestroy()
        thread = null
    }

    override fun getLayoutResId(): Int = R.layout.examine_class_do_attendance_activity

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        classId = intent.getStringExtra("classId")
        setViewTitle("签到打卡", "签到记录") {
            XUtils.intent().openActivity(this@ExamineClassDoAttendanceActivity, ExamineAttendanceHistoryActivity::class.java)
                .putStringExtra("classId", classId).start()
        }

        viewModel = ExamineViewModel()
        doAttendanceItem.setOnClickListener {
            doAttendance()
        }
        attendanceVO.classId = classId
        initView()

        viewModel!!.getSchoolAttendanceList(classId!!)
    }

    private fun initTimer() {
        val format = SimpleDateFormat("HH:mm:ss")
        currTimeTv.text = format.format(Date())

        thread = Thread {
            Thread.sleep(1000)
            do {
                try {
                    Thread.sleep(1000)
                    runOnUiThread {
                        currTimeTv.text = format.format(Date())
                    }
                } catch (e: InterruptedException) {
                    e.printStackTrace()
                }
            } while (true)

        }
        thread?.start()
    }

    private fun doAttendance() {

        attendanceVO.userId = LocalCache.getLoginUserId()

        showLoadingDialog("正在提交")
        viewModel?.doAttendance(attendanceVO)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public fun eventBusCallback(result: ResultInfo<AttendanceEntity>) {
        if (result.eventType != "doAttendance") {
            return
        }

        hideLoadingDialog()

        when (result.code) {
            ResultInfo.SUCCESS -> {
                if (result.data != null) {
                    XUtils.toast().show("打开成功")
                    if ("sign" == attendanceVO.checkType) {
                        signTimeTv.text = XUtils.string().getNotNullValue(result.data.createTime)
                    } else {
                        outTimeTv.text = XUtils.string().getNotNullValue(result.data.createTime)
                    }

                    viewModel!!.getSchoolAttendanceList(classId!!)
                } else {
                    XUtils.toast().show(result.msg)
                }
            }
            ResultInfo.TOKEN_OVERDUE -> {
            }
            else -> {
                XUtils.toast().show(result.msg)
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public fun attendanceListCallback(result: ResultInfo<List<AttendanceEntity>>) {
        if ("getSchoolAttendanceList" != result.eventType) {
            return
        }

        when (result.code) {
            ResultInfo.SUCCESS -> {
                if (result.data == null || result.data.isEmpty()) {
                    showSign()
                } else if (result.data.size == 1) {
                    showTimeInfo(result.data)
                    showOut()
                } else {
                    attendanceDisable()
                    showTimeInfo(result.data)
                }
            }
            else -> {
                XUtils.toast().show(result.msg)
            }
        }
    }

    private fun showSign() {
        localInfoItem.visibility = View.VISIBLE

        attendanceVO.checkType = "sign"
        currTypeTv.text = "签到"
        signItem.setBackgroundResource(R.drawable.selector_bg_attendance)
        signFlag.setTextColor(ContextCompat.getColor(this, R.color.white))
        signTimeTv.setTextColor(ContextCompat.getColor(this, R.color.white))

        outItem.setBackgroundResource(R.color.app_bg)
        outFlag.setTextColor(ContextCompat.getColor(this, R.color.page_title))
        outTimeTv.setTextColor(ContextCompat.getColor(this, R.color.page_sub))
    }

    private fun showOut() {
        localInfoItem.visibility = View.VISIBLE

        attendanceVO.checkType = "out"
        currTypeTv.text = "签退"

        signItem.setBackgroundResource(R.color.app_bg)
        signFlag.setTextColor(ContextCompat.getColor(this, R.color.page_title))
        signTimeTv.setTextColor(ContextCompat.getColor(this, R.color.page_sub))

        outItem.setBackgroundResource(R.drawable.selector_bg_attendance)
        outFlag.setTextColor(ContextCompat.getColor(this, R.color.white))
        outTimeTv.setTextColor(ContextCompat.getColor(this, R.color.white))
    }

    private fun attendanceDisable() {
        doAttendanceItem.isClickable = false
        currTypeTv.text = "已打卡"
        localInfoItem.visibility = View.GONE

        signItem.setBackgroundResource(R.color.app_bg)
        signFlag.setTextColor(ContextCompat.getColor(this, R.color.page_title))
        signTimeTv.setTextColor(ContextCompat.getColor(this, R.color.page_sub))

        outItem.setBackgroundResource(R.color.app_bg)
        outFlag.setTextColor(ContextCompat.getColor(this, R.color.page_title))
        outTimeTv.setTextColor(ContextCompat.getColor(this, R.color.page_sub))
    }

    private fun showTimeInfo(attendanceList: List<AttendanceEntity>) {
        for (attendance in attendanceList) {
            if ("sign" == attendance.checkType) {
                signTimeTv.text = XUtils.string().getNotNullValue(attendance.createTime)
            } else {
                outTimeTv.text = XUtils.string().getNotNullValue(attendance.createTime)
            }
        }
    }
}